package com.mediacloud.app.newsmodule.fragment.newslist;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.mediacloud.app.assembly.banner.NetImageBanner;
import com.mediacloud.app.assembly.banner.NetImageBanner.OnItemClickListener;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.model.component.ComponentItem;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleListData;
import com.mediacloud.app.model.news.BaseMessageReciver;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.model.news.kt.TypeX;
import com.mediacloud.app.model.view.floatwin.FloatButtonGroup;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.adaptor.component.BannerView;
import com.mediacloud.app.newsmodule.fragment.BaseNewsListFragment;
import com.mediacloud.app.newsmodule.fragment.ListPreLoadTool;
import com.mediacloud.app.newsmodule.utils.BindEventBus;
import com.mediacloud.app.newsmodule.utils.CacheDataKt;
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.enums.StyleOther;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 新闻内容列表页 带banner
 */
public class NewsListWidthBannerFragment extends
        BaseNewsListFragment implements OnItemClickListener {
  // protected NetImageBannerX banner;
   protected BannerView bannerView;
    protected List<ArticleItem> bannerData;
    protected int maxBannerSize;

    public static final String HAVE_BANNER = "1";


    public NewsListWidthBannerFragment() {

        bannerData = new ArrayList<ArticleItem>();
        String bannerDefNum = AppFactoryGlobalConfig.getAppServerConfigInfo(getActivity()) != null ? AppFactoryGlobalConfig.getAppServerConfigInfo(getActivity()).getContent_list_banner() : "3";
        maxBannerSize = TextUtils.isEmpty(bannerDefNum) ? 3 : Integer.valueOf(bannerDefNum);
    }
    @Override
    protected Class<? extends BaseDataInvokeCallBack<? extends BaseMessageReciver>> getDataInvokeCallBackClass() {
        return NewsListDataInvokeCallBack.class;
    }

    @Override
    public void initView() {
        super.initView();
        new BindEventBus(this,adaptor);
    }

    @Override
    public void beforeUserCache() {
        super.beforeUserCache();
        doRefresh();
        //爆料排行列表新ui不加banner
        if (catalogItem != null && catalogItem.getCatalogStyle() != StyleOther.OtherStyle
                &&!AppFactoryGlobalConfig.FeatureModule.BigModule.BAO_LIAO_RANK.equals(catalogItem.getCatalog_type())
                && HAVE_BANNER.equals(getActivity().getResources().getString(R.string.newslist_havebanner)))
            addBanner();
    }

    protected void addBanner() {
        bannerView = new BannerView(requireContext());
        ViewGroup.LayoutParams  lp = new ViewGroup.LayoutParams(-1, (int) (Utility.getScreenWidth(requireContext())*9f/16));
        headerViewContainer.addView(bannerView, 0,lp);
        haveBanner = true;
//        banner = new NetImageBannerX(getActivity());
//        //		banner.allowLoopTouch=false;
//        int mainColor = Color.parseColor(AppFactoryGlobalConfig.getAppServerConfigInfo(getActivity()).getColor());
//        banner.currentFocusItemColor = mainColor;
//        banner.defaultLoadBackground = AppFactoryGlobalConfig.getDefaultImagLoadBackground();
//        //		NetImageBanner.DefaultDelta=(float) (1.0/2.0f);
//        int bannerHeight = (int) (getResources().getDisplayMetrics().widthPixels * banner.DefaultDelta);
//        banner.defaultHeight = bannerHeight;
//        headerViewContainer.addView(banner, 0);
////		headerViewContainer.addView(banner);//不指定位置试试
//        banner.dotContainer.setVisibility(View.VISIBLE);
//        banner.currentImage.setVisibility(View.GONE);
//        haveBanner = true;
//        banner.setOnItemClickListener(this);
    }

    @Override
    public int getLayoutResID() {
        return R.layout.fragment_news_itemcontent;
    }

    protected void refreshBanner() {
        if (bannerData.size() == 0 || attached == false){
            bannerView.setVisibility(View.GONE);
            return;
        }
        bannerView.setVisibility(View.VISIBLE);
        bannerView.setData(bannerData);
//        banner.cleanAll();
//        for (ArticleItem item : bannerData) {
//            banner.addItem(item.getLogo(), PayTipsUtilsKt.payTips(item, getActivity(), getActivity().getResources().getString(R.string.pay_a_pei), getActivity().getResources().getDimension(R.dimen.pay_label_size), (int) getActivity().getResources().getDimension(R.dimen.pay_label_bgradius)), AppFactoryGlobalConfig.getDefaultImageLoadDrawable(), item.getType());
//        }
//        int bannerHeight = (int) (getResources().getDisplayMetrics().widthPixels * banner.DefaultDelta);
//        banner.defaultHeight = bannerHeight;
//        banner.updateLayout();
    }

    @Override
    public void onClick(NetImageBanner banner, int position, Object tag) {
        ArticleItem item = bannerData.get(position);
        item.setParentId(catalogID);
        NewsItemClickUtils.OpenItemNewsHandle(getActivity(), item.getType(), item, catalogItem);
    }

    public class NewsListDataInvokeCallBack extends BaseDataInvokeCallBack<ArticleListData> {
        @Override
        public void success(final ArticleListData result) {
            if (getActivity() == null || requireActivity().isFinishing()||requireActivity().isDestroyed()) {
                return ;
            }
            Log.w("APPTAG", "success");
            boolean isCacheData = false;
            if (needCache() && pageNum == 1) {
                //不是上次的缓存数据才进行缓存
                isCacheData = result.orginData.optInt("is_cache",0)==1;
                if(!isCacheData){
                    try {
                        result.orginData.put("is_cache",1);
                        CacheDataKt.saveData(NewsListWidthBannerFragment.this, catalogID, result.orginData + "");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }


            if (adaptor == null)
                return;
            isLoading = false;
            JSONObject data = result.orginData.optJSONObject("data");
            if(pageNum==1){
                if (FloatButtonGroup.haveFloatField(data)) {
                    initFloatWin(data);
                } else {
                    hideFloatWin();
                }
            }
            if (pageNum == 1 && !result.haveMore() &&
                    result.articleList != null && result.articleList.size() == 0) {
                ArticleItem footerEmptyArticleItem = new ArticleItem();
                footerEmptyArticleItem.setType(TypeX.CUSTOM.Footer_Empty);
                result.articleList.add(footerEmptyArticleItem);
                isAddFooterEmptyArticleItem = true;
            }
            if (pageNum == 1) {
                mXSmartRefreshLayout.finishRefresh();
                //加一个31组件（两行文字的顶栏组件）的头部
                // (这里的逻辑是顶栏组件移动到头部，移除它在组件中的位置，保证它置顶)
                if (needAddComponent31(result.componentItems) && haveBanner) {
                    addComponent31Header(result);
                }

                //添加一个36组件到头部
                if (needAddComponent36(result.componentItems)) {
//                    addComponent36Header(result);
                }
//								if(haveBanner&&result.articleList.size()>maxBannerSize)
                if (haveBanner && !needRemoveSelfBanner(result.componentItems)) {
                    bannerData.clear();
                    int maxSize = result.articleList.size() >= maxBannerSize ? maxBannerSize : result.articleList.size();
                    for (int i = 0; i < maxSize; i++) {
                        if (maxSize==1&&result.articleList.get(i).getType()==TypeX.CUSTOM.Footer_Empty){
                            break;
                        }
                        bannerData.add(result.articleList.remove(0));
                    }
                    attached = true;
                    refreshBanner();
                }
//                else if (banner != null) {
//                    banner.defaultHeight = 0;
//                    banner.cleanAll();
//                    banner.updateLayout();
//                }
                if (adaptor.getListContentData() != null)
                    adaptor.getListContentData().clear();
                //添加组件  用的HeadView
              //  componetContainer.updateComponent(result.componentItems);
                for (int i = 0; i < result.componentItems.size(); i++) {
                    result.componentItems.get(i).belongNavId = catalogID;
                }
                bufferComponentContainer.setData(result.componentItems,catalogItem);
            }
            if (result.more)
                mXSmartRefreshLayout.finishLoadMore();
            else
                mXSmartRefreshLayout.finishLoadMoreWithNoMoreData();

            ListPreLoadTool.preLoad(requireContext(), result.articleList);
            if (adaptor.getListContentData() == null)
                adaptor.setListContentData(result.articleList);
            else
                adaptor.getListContentData().addAll(
                        result.articleList);

            adaptor.notifyDataSetChanged();
            if (isAddFooterEmptyArticleItem) {
                if (bannerData.size() == 0 && (adaptor.getListContentData() == null || adaptor.getListContentData().size() <= 1) && result.componentList.size() == 0) {
                    showStateView(TYPE_NO_CONTENT, false);
                } else
                    closeStateView();
            }
            else{
                if (bannerData.size() == 0 && (adaptor.getListContentData() == null || adaptor.getListContentData().size() == 0) && result.componentList.size() == 0) {
                    showStateView(TYPE_NO_CONTENT, false);
                } else
                    closeStateView();
            }
            if(isCacheData ){
//                mXSmartRefreshLayout.autoRefresh(400);
                onRefresh(mXSmartRefreshLayout);
            }
            dataReady = true;
            if(!isCacheData){
                contentListCache.setPageNum(pageNum + 1);
                contentListCache.preload2();
                if(pageNum==1){
                    //触发一下 onScrollStateChanged 否则 视频不会自动播放
                    mCatalogContentItemListView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if(onScrollListener != null){
                                onScrollListener.onScrollStateChanged(mCatalogContentItemListView, AbsListView.OnScrollListener.SCROLL_STATE_IDLE);
                            }
                        }
                    },300);
                }
            }
        }
    }

//    private void addComponent36Header(ArticleListData result) {
//        ComponentItem item = result.componentItems.remove(0);
//        if (!haveAddComponent36) {
//            try {
//                haveAddComponent36 = true;
//                View view = LayoutInflater.from(getActivity()).inflate(R.layout.component_type36, null);
//                RecyclerView recyclerView = view.findViewById(R.id.recyclerview);
//                recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
//                TopArticleAdapter topArticleAdapter = new TopArticleAdapter(R.layout.item_top_article);
//                topArticleAdapter.bindToRecyclerView(recyclerView);
//                headerViewContainer.addView(view, 0);
//                String element = item.element;
//                String lable = item.orginDataObject.optJSONObject("other_field").optString("lable");
//                final List<ArticleItem> articleItemList = JSON.parseArray(element, ArticleItem.class);
//                if (articleItemList != null && articleItemList.size() != 0) {
//                    topArticleAdapter.setLabel(lable);
//                    topArticleAdapter.setNewData(articleItemList);
//                    topArticleAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//                        @Override
//                        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                            ArticleItem articleItem = (ArticleItem) adapter.getItem(position);
//                            NewsItemClickUtils.OpenItemNewsHandle(getActivity(), articleItem.getType(), articleItem, new CatalogItem());
//                        }
//                    });
//                }
//
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//    }

    /**
     * 如果存在31组件和banner时，就采用这种操作把这个31组件放到头部
     */
    protected void addComponent31Header(ArticleListData result) {
        ComponentItem item = result.componentItems.remove(0);
        if (!haveAddComponent31) {
            try {
                View view = LayoutInflater.from(getActivity()).inflate(R.layout.component_type31, null);
                TextView bigTitleTv = view.findViewById(R.id.text_big_title);
                TextView smallTitleTv = view.findViewById(R.id.text_small_title);
                headerViewContainer.addView(view, 0);
                haveAddComponent31 = true;
                String element = item.element;
                final List<ArticleItem> articleItemList = JSON.parseArray(element, ArticleItem.class);
                if (articleItemList.size() != 0) {
                    bigTitleTv.setText(articleItemList.get(0).getTitle());
                    bigTitleTv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //是否为大图样式，大图样式采用新的图集详情页
                            NewsItemClickUtils.OpenItemNewsHandle(getActivity(), articleItemList.get(0).getType(), articleItemList.get(0), new CatalogItem());
                        }
                    });
                }
                if (articleItemList.size() > 0) {
                    smallTitleTv.setText(articleItemList.get(1).getTitle());
                    smallTitleTv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            NewsItemClickUtils.OpenItemNewsHandle(getActivity(), articleItemList.get(1).getType(), articleItemList.get(1), new CatalogItem());
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
//        if (banner != null) {
//            banner.cleanAll();
//        }
    }
}